package com.zhenwgang.listen_books.servlet.album;

import com.zhenwgang.listen_books.service.AlbumService;
import com.zhenwgang.listen_books.util.Log;
import com.zhenwgang.listen_books.view_object.UserVO;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Violet
 * @date 2022/07/12 19:48
 **/
@WebServlet("/studio/album/bind.json")
public class BindJsonServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final AlbumService albumService = new AlbumService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        UserVO currentUser = null;

        if (session != null){
            currentUser = (UserVO) session.getAttribute("currentUser");
        }

        if (currentUser == null){
            throw new RuntimeException("用户未登录");
        }

        Log.println("用户已登录");

        int aid = Integer.parseInt(req.getParameter("aid"));
        Log.println(aid);

        Object view = albumService.getBindInfo(currentUser, aid);

        String json = objectMapper.writeValueAsString(view);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.println(json);
    }
}